﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging; 

namespace Lee.Utility
{
    [ProviderAlias("File")]
    public class FileLoggerProvider : ILoggerProvider
    {
        private  LoggerExternalScopeProvider _scopeProvider=new LoggerExternalScopeProvider();
        public ILogger CreateLogger(string categoryName)
        {
            var logger = new FileLogger(categoryName,_scopeProvider);
            return logger;
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }

    public class FileLogger : ILogger
    {
        private readonly string categoryName;

        private IExternalScopeProvider ScopeProvider { get; set; }
        public FileLogger(string categoryName, IExternalScopeProvider scopeProvider)
        {
           this.categoryName = categoryName;
            this.ScopeProvider = scopeProvider;
        }
        public  IDisposable BeginScope<TState>(TState state)
        {
            return ScopeProvider.Push(state);
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return logLevel != LogLevel.None;
        } 
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            var currentPath = Directory.GetCurrentDirectory();
            var path = Path.Combine(currentPath, $"{DateTime.Now:yyyy:MM-dd}.log");
            var message = formatter(state, exception);
            File.AppendAllText(path, $"{logLevel}:{categoryName} {DateTime.Now} \r\n {message} \r\n");
        }
    }

    public static class FileLoggerExtensions
    {
        public static ILoggingBuilder AddFile(this ILoggingBuilder builder)
        {
            builder.Services.TryAddEnumerable(Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton<ILoggerProvider, FileLoggerProvider>());
            return builder;
        }
    }
}
